<template>
  <el-dialog
    v-model="dialogVisible"
    title="Tips"
    width="30%"
    :before-close="() => $emit('handleClose')"
  >
    <!-- <span>This is a message</span> -->
    <el-form ref="FormRef" :model="dataForm" :rules="formRules">
      <el-form-item label="姓名" prop="name">
        <el-input v-model="dataForm.name"></el-input>
      </el-form-item>
      <el-form-item label="年龄" prop="age">
        <el-input v-model="dataForm.age"></el-input>
      </el-form-item>
      <el-form-item label="性别" prop="sex">
        <el-select v-model="dataForm.sex">
          <el-option :value="1" label="男"></el-option>
          <el-option :value="2" label="女"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="出生日期" prop="date">
        <el-date-picker
          v-model="dataForm.date"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="Pick a day"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="$emit('handleClose')">取消</el-button>
        <el-button type="primary" @click="doSubmit">提交</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import type { FormRules } from 'element-plus';
import {reactive, ref} from 'vue'
interface RuleForm {
  name: string
  age: number | undefined
  date: string
  sex: number
}
const emits = defineEmits(['handleClose'])
const {id} = defineProps(['id'])
let dataForm = ref<RuleForm>({
  name: '',
  age: undefined,
  date: '',
  sex: 1
})
console.log(id)
if(id) {
  //调用接口拿到这个id对应的数据的详情
  setTimeout(() => {
    const res = {name: '张学友', age: 20, sex: 2, date: '2023-12-29'}
    dataForm.value = {
      name: res.name,
      age: res.age,
      sex: res.sex,
      date: res.date
    }
  }, 2000)
}
const dialogVisible = true
const FormRef = ref()

const formRules = reactive<FormRules<RuleForm>>({
  name: [{required: true, message: '请输入姓名', trigger: 'blur'}],
  age: [
  {required: true, message: '请输入年龄', trigger: 'blur'}]
})
const doSubmit = () => {
  FormRef.value.validate((valid: boolean) => {
    if (valid) {
      //构造添加用户接口使用的参数
      let params:{
        name: string
        age: number | undefined
        sex: number
        id?: string
        date: string
      } = {
        name: dataForm.value.name,
        age: dataForm.value.age,
        sex: dataForm.value.sex,
        date: dataForm.value.date
      }
      if(id) {
        params.id = id
      }
      //调用接口吧params传到接口
      console.log('submit!')
      //接口成功之后
      emits('handleClose', true)

    } else {
      console.log('error submit!')
      return false
    }
  })
  //调用添加用户的接口
}
</script>

<style></style>
